﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HB.Base;
using HB.Expand;
namespace SimpleWatch
{
    public class DirWatch
    {
        FileSystemWatcher watch { get; set; }
        AverageSpeed speed = new AverageSpeed(3);
        public ulong ChangedTimes { get; set; }
        public string Dir { get; set; }
        public double Speed { get; set; }
        public string TimeText { get; set; }
        public DirWatch(string dir, Action OnCallback)
        {
            watch = new FileSystemWatcher();
            watch.EnableRaisingEvents = false;
            watch.IncludeSubdirectories = true;
            watch.Path = dir;
            this.Dir = dir;
            watch.EnableRaisingEvents = true;

            watch.Changed += (a, b) =>
            {
                OnCallback.Invoke();
            };
            watch.Deleted += (a, b) =>
            {
                OnCallback.Invoke();
            };
            watch.Created += (a, b) =>
            {
                OnCallback.Invoke();
            };
            watch.Renamed += (a, b) =>
            {
                OnCallback.Invoke();
            };
            speed.OnSpeedChanged += Speed_OnSpeedChanged;
        }

        private void Speed_OnSpeedChanged(double obj)
        {
            Speed = obj;
        }

        public void AddOne()
        {
            lock (watch)
            {
                ChangedTimes += 1;
                speed.Log();
                TimeText = ToSize(ChangedTimes);
            }
        }
        public string ToSize(double times)
        {
            string util = "";
            if (times > 1000) { times /= 1000; util = "K"; }
            if (times > 1000) { times /= 1000; util = "M"; }
            if (times > 1000) { times /= 1000; util = "G"; }
            if (times > 1000) { times /= 1000; util = "T"; }
            if (times > 1000) { times /= 1000; util = "P"; }
            return $"{times.ToString("f2")} {util}";
        }
    }
}
